<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear='getUsersList'>
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="showAddDialog"> 添加用户</el-button>
        </el-col>
      </el-row>
      <el-table border stripe :data="usersList" style="width: 100%">
        <el-table-column type="index" label="#" width="40">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="100">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change='saveUserState(scope.row)'>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="showeditDialog(scope.row.id)" size="mini" type="primary" icon="el-icon-edit"></el-button>
            <el-button @click="removeById(scope.row.id)" size="mini" type="danger" icon="el-icon-delete"></el-button>
            <el-tooltip :enterable='false' effect="dark" content="分配角色" placement="top">
              <el-button size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 3, 8, 10,15,20,30]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" @close='addUserDialogClose' :visible.sync="addDialogVisible" width="50%">
      <el-form :model="addUsersForm" :rules="addUsersFormRules" ref="addUsersFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUsersForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUsersForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUsersForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUsersForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog title="修改用户" @close='editUserDialogClose' :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editUsersForm" :rules="editUsersFormRules" ref="editUsersFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUsersForm.username " disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUsersForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUsersForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const mobilePass = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        return callback(new Error('请输入合法的手机号码'))
      }
    }
    const emailPass = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return callback()
      } else {
        return callback(new Error('请输入合法email'))
      }
    }
    return {
      queryInfo: {
        query: '',
        pagesize: 3,
        pagenum: 1
      },
      total: 0,
      usersList: [],
      addDialogVisible: false,
      addUsersForm: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      addUsersFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: mobilePass, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailPass, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editUsersForm: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      editUsersFormRules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: mobilePass, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emailPass, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.usersList = res.data.users
      this.total = res.data.total
    },
    handleCurrentChange(page) {
      this.queryInfo.pagenum = page
      this.getUsersList()
    },
    handleSizeChange(size) {
      this.queryInfo.pagesize = size
      this.getUsersList()
    },
    showAddDialog() {
      this.addDialogVisible = true
    },
    addUserDialogClose() {
      this.$refs.addUsersFormRef.resetFields()
    },
    addUserSubmit() {
      this.$refs.addUsersFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addUsersForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        this.getUsersList()
        this.addDialogVisible = false
      })
    },
    async saveUserState(row) {
      const { data: res } = await this.$http.put(`users/${row.id}/state/` + row.mg_state)
      if (res.meta.status !== 200) {
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
      this.getUsersList()
    },
    async showeditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败！')
      }
      this.editUsersForm = res.data
      this.editDialogVisible = true
    },
    editUserDialogClose() {
      this.$refs.editUsersFormRef.resetFields()
    },
    editUserSubmit() {
      this.$refs.editUsersFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editUsersForm.id, {
          mobile: this.editUsersForm.mobile,
          email: this.editUsersForm.email
        })

        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败！')
        }

        this.$message.success('修改用户信息成功！')
        this.getUsersList()
        this.editDialogVisible = false
      })
    },
    async removeById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败!')
      }
      this.$message.success('删除成功!')
      this.getUsersList()
    }
  }
}
</script>
